<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/all.conf.php');
require_once(__PHY_WEB.__DIR_ADM.'/admin.inc.php');
require_once(__PHY_LIB.'/class/uWork.class.php');
require_once(__PHY_LIB.'/class/uUser.class.php');
require_once(__PHY_LIB.'/class/uCategory.class.php');

$rReq = validate($_REQUEST, 'msg:u|action:e[list,edit,update]');
$sMsg = $rReq['msg'];
$sAction = $rReq['action'];

if ('update' == $sAction) {
	$oOne = new uWork($_POST['id']);
	$rP = validate($_POST, 'title:u|price:f|tags:u|description:u');
	foreach ($rP as $sField => $xValue) {
		$oOne->set($sField, $xValue);
	}
	if (!(0 < $_POST['id'])) {
		$sMsg .= "没有ID无法修改。".$_br;
	}
	elseif ($s = $oOne->invalid()) {
		$sMsg .= "参数不规范: {$s}".$_br;
	}
	elseif ($oOne->update()) {
		$sMsg .= '修改成功。'.$_br;
	}
	else {
		$sMsg .= '修改失败'.$_br;
	}
	$sAction = 'list';
}

if ('edit' == $sAction) {
	$oOne = new uWork($_REQUEST['id']);
	$oUser = new uUser($oOne->get('owner_id'), 'nick');
	$oOne->set('owner_nick', $oUser->get('nick'));
	$oCtgry = new uCategory($oOne->get('category_id'));
	$oOne->set('BreadCrumb', $oCtgry->fetchBreadCrumb());
	$oTpl->assign('rOne', $oOne->getData());
}
elseif ('list' == $sAction) {
	$rP = validate($_GET, 'category:n|pg:n');
	$oTpl->assign('rP', $rP);
	$sWhere = "TRUE";
	/// 按类别查找 ///
	$oCtgry = new uCategory($rP['category']);
	if (0 < $oCtgry->getID()) {
		$sWhere .= " AND category_id IN ('".implode("','", $oCtgry->getTreeIdsByTop($oCtgry->getID()))."')";
	}
	/// 作品列表 ///
	$rPager = array(
		'Sze' => 25,
		'Req' => 'pg',
		'Num' => max(1, $rP['pg']),
		'Bse' => http_build_query(array_slice($rP, 0, -1)),
	);
	$oList = new uWorkList();
	$oList->cfgWhere($sWhere);
	$rPager['Cnt'] = $oList->countAll();
	$rPager['Max'] = ceil($rPager['Cnt']/$rPager['Sze']);
	$oList->cfgOrder("id DESC");
	$oList->load($rPager['Sze']*($rPager['Num'] - 1), $rPager['Sze']);
	while ($oOne = $oList->nextItem()) {
		$oUser = new uUser($oOne->get('owner_id'), 'nick');
		$oOne->set('owner_nick', $oUser->get('nick'));
		$oCtgry = new uCategory($oOne->get('category_id'));
		$oOne->set('BreadCrumb', $oCtgry->fetchBreadCrumb());
	}
	$oTpl->assign('rList', $oList->fetchArray());
	$oTpl->assign('rPager', $rPager);
}

/// 类别目录列表 ///
$oCtgryList = new uCategoryList();
$oCtgryList->cfgOrder("tree");
$oCtgryList->load();
while ($oCtgry = $oCtgryList->nextItem()) {
	$sBreadCrumb = '';
	foreach ($oCtgry->fetchBreadCrumb() as $r) {
		$sBreadCrumb .= $r['title'].' > ';
	}
	$oCtgry->set('BreadCrumb', substr($sBreadCrumb, 0, -3));
}
$oTpl->assign('rSlctCtgrys', $oCtgryList->fetchArray());

$oTpl->assign('sMsg', $sMsg);
$oTpl->assign('sAction', $sAction);
$oTpl->display(dirname(__FILE__).'/'.basename(__FILE__, '.php').'.tpl');
?>
